package org.testis.communication.client;

import java.io.IOException;
import net.sbbi.upnp.Discovery;
import net.sbbi.upnp.devices.UPNPRootDevice;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * A class to define an UPNP client to detect devices 
 * @author nurhat
 */
public class AtofUpnpClient {

    /**
     * Gets all devices for the given device type.
     * Compares if any of these devices has the given serial id.
     * @param deviceType
     * @param deviceSerialId
     * @return true if a device found for the given serial id 
     * @throws java.io.IOException
     */
    public boolean checkIfDeviceExist(String deviceType,
            String deviceSerialId) {
        try {
            Logger.getLogger("net.sbbi.upnp.devices.UPNPRootDevice").
                    setLevel(Level.OFF);
            boolean result = false;

            UPNPRootDevice[] devices = null;

            devices = Discovery.discover(deviceType);

            if (devices != null) {
                for (int i = 0; i < devices.length;
                        i++) {
                    if (devices[i] == null) {
                    } else if (devices[i].getSerialNumber() == null) {
                    } else if (devices[i].getSerialNumber().equals(deviceSerialId)) {
                        result = true;
                        break;
                    }
                }
            }
            return result;
        } catch (IOException ex) {
        }
        return false;
    }

    public UPNPRootDevice[] getDeviceList(String deviceType) {
        try {
            Logger.getLogger("net.sbbi.upnp.devices.UPNPRootDevice").
                    setLevel(Level.OFF);

            UPNPRootDevice[] devices = null;

            devices = Discovery.discover(deviceType);
            return devices;
        } catch (IOException ex) {
        }
        return null;

    }
}

